import jinja2, os, webapp2, urllib, cgi
from google.appengine.ext import db
from google.appengine.api import mail, users
from displugged import navbar
from datatypes import *
import sessions

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class send(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/message_send.html')
        replyid = urllib.unquote(self.request.get("replyid"))
        replyall = urllib.unquote(self.request.get("all"))
        sendto = urllib.unquote(self.request.get("sendto"))
        if sendto!='':
            self.response.out.write(template.render({'receivers':db.get(sendto).username,'navbar': navbar(self)}))
        elif replyid!='':
            # error checking on replyid would be nice
            tostring=''
            reply_message = db.get(replyid)
            sender = reply_message.sender.username
            for receiver in reply_message.receivers:
                receiving = db.get(receiver).username
                if receiving != sessions.ourUserModel().username:
                    tostring+=receiving+','
            if sender!=sessions.ourUserModel().username:
                tostring+=sender
            else:
                tostring=tostring[0:-1] #crude way of removing last comma
            if replyall=='0':
                self.response.out.write(template.render({'receivers':sender,'subject' : 'RE: '+db.get(replyid).subject,'navbar': navbar(self)}))
            elif replyall=='1':
                self.response.out.write(template.render({'receivers':tostring,'subject' : 'RE: '+db.get(replyid).subject,'navbar': navbar(self)}))
        else:
            self.response.out.write(template.render({'navbar': navbar(self)}))
    def post(self):
        to = urllib.unquote(self.request.get("receivers"))
        subject = urllib.unquote(self.request.get("subject"))
        message = urllib.unquote(self.request.get("message"))
        receivers = []
        for person in to.split(','):
            person=person.strip();
            result = User.all().ancestor(UserPathGen()
                    ).filter('username =', person)
            if result.count()==1:
                receivers.append(result.get().key())
            else:
                self.response.out.write("The user %s was not found.<br />"%cgi.escape(person))
        newMessage = Communication(parent = MessagePathGen())
        newMessage.sender = sessions.ourUserModel()
        newMessage.message = message
        newMessage.subject = subject
        newMessage.receivers = receivers
        
        newMessage.put()

        self.response.out.write(
            "Your message has been sent!")

class inbox(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/inbox.html')
        self.response.out.write(template.render({'navbar': navbar(self)}))
        results = Communication.all().ancestor(MessagePathGen()
                    ).filter('receivers =', sessions.ourUserModel().key())
        self.response.out.write("<table border='1'><tr><td><b>From</b></td><td><b>Subject</b></td></tr>")
        for result in results:
            self.response.out.write("<tr>")
            self.response.out.write("<td>%s</td>"%cgi.escape(result.sender.username))
            self.response.out.write("<td><a href='/communicate/mail?mailid=%s'>%s</a></td>"%(urllib.quote(str(result.key())),cgi.escape(result.subject)))
            self.response.out.write("</tr>")
        self.response.out.write("</table>")

class mail(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/inbox.html') # MIGHT WANT TO CHANGE THIS TEMPLATE
        self.response.out.write(template.render({'navbar': navbar(self)}))
        key = urllib.unquote(self.request.get("mailid"))
        message = db.get(key)
        if((sessions.ourUserModel().key() in message.receivers)
           or (sessions.ourUserModel().key() == message.sender.key())):
            self.response.out.write("From: %s"%cgi.escape(message.sender.username))
            self.response.out.write("<br />To: ")
            for receiver in message.receivers:
                self.response.out.write(cgi.escape(db.get(receiver).username+', '))
            self.response.out.write("<br />Subject: %s"%cgi.escape(message.subject))
            self.response.out.write("<br /><br />Message:<br />%s"%cgi.escape(message.message))
            self.response.out.write(
                "<br /><br /><a href = '/communicate/send?replyid=%s&all=0&'>Reply</a> <a href = '/communicate/send?replyid=%s&all=1'>Reply All</a>"%(
                message.key(),message.key()))
        else:
            #no permission
            self.redirect('/communicate/inbox')

class sent(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/inbox.html') # MIGHT WANT TO CHANGE THIS TEMPLATE
        self.response.out.write(template.render({'navbar': navbar(self)}))
        results = Communication.all().ancestor(MessagePathGen()
                    ).filter('sender =', sessions.ourUserModel())
        self.response.out.write("<table border='1'><tr><td><b>To</b></td><td><b>Subject</b></td></tr>")
        for result in results:
            self.response.out.write("<tr>")
            tostring=''
            for receiver in result.receivers:
                tostring+=db.get(receiver).username+','
            tostring=tostring[0:-1]
            self.response.out.write("<td>%s</td>"%tostring)
            self.response.out.write("<td><a href='/communicate/mail?mailid=%s'>%s</a></td>"%(result.key(),result.subject))
            self.response.out.write("</tr>")
        self.response.out.write("</table>")

app = webapp2.WSGIApplication([('/communicate/send', send),
                               ('/communicate/inbox',inbox),
                               ('/communicate/mail',mail),
                               ('/communicate/sent',sent)],
                              debug=True)
